package com.seed.application.gateway;

import com.seed.application.Sa;
import com.seed.application.gateway.impl.DevSeedGateway;
import com.seed.application.gateway.impl.MicroSeedGateway;
import com.seed.application.gateway.impl.SingleSeedGateway;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Slf4j
public class SeedFilter implements Filter {

    private final SeedGateway seedGateway;

    public SeedFilter() {
        seedGateway = switch (Sa.getMode()) {
            case dev -> new DevSeedGateway();
            case single -> new SingleSeedGateway();
            default -> new MicroSeedGateway();
        };
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String uri = request.getRequestURI();
        log.info("请求地址【{}】", uri);

        if(isWhiteList(uri)) { //1. 白名单地址
            chain.doFilter(req, res);
            return;
        }

        seedGateway.doFilter(request, response, chain);
    }

    private boolean isWhiteList(String uri) {
        List<String> anon = List.of("/webjars", "/doc.html", "/v3", "/favicon.ico", "/error");
        for(String pre: anon) {
            if(uri.startsWith(pre)) return true;
        }

        return false;
    }
}
